// @ts-ignore
import {http} from '@/uni_modules/uview-plus';

// 混入默认个性化配置
function mixinCustom(config: any) {
    config.custom = Object.assign({
        auth: true,
        toast: true,
        catch: true,
        loading: true
    }, config.custom || {});
    return config;
}

// 格式化get请求url参数
function urlFormater(url: string, params: any) {
    if (params) {
        const paramList = Object.keys(params).map(key => `${key}=${params[key]}`);
        return url.includes('?') ? `${url}&${paramList.join('&')}` : `${url}?${paramList.join('&')}`;
    }
    return url;
}

const request = {
    // post 方法，params 和 config 设为可选参数
    post(url: string, params?: any, config?: any) {
        // 若 config 未传入，初始化为空对象
        config = config || {};
        config = mixinCustom(config);
        return http.post(url, params, config);
    },

    // uploadFile 方法，config 设为可选参数
    uploadFile(url: string, config?: any) {
        config = config || {};
        config = mixinCustom(config);
        return http.upload(url, config);
    },

    // get 方法，params 和 config 设为可选参数
    get(url: string, params?: any, config?: any) {
        config = config || {};
        config = mixinCustom(config);
        const path = urlFormater(url, params);
        return http.get(path, config);
    },

    // put 方法，params 和 config 设为可选参数
    put(url: string, params?: any, config?: any) {
        config = config || {};
        config = mixinCustom(config);
        return http.put(url, params, config);
    },

    // delete 方法，params 和 config 设为可选参数
    delete(url: string, params?: any, config?: any) {
        config = config || {};
        config = mixinCustom(config);
        return http.delete(url, params, config);
    }
};

export default request;